package com.jxud.utils;

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;

import java.io.File;
import java.io.InputStream;
import java.util.UUID;

import com.aliyuncs.exceptions.ClientException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;
@Component
public class AliOSSUtils {
    @Value("${aliyun.oss.endpoint}")  //https://oss-cn-beijing.aliyuncs.com
    private String endpoint;
    @Value("${aliyun.oss.bucketName}") //web-tlais-jxd
    private String bucketName;
    @Value("${aliyun.oss.accessKeyId}")   //LTAI5tPa5Yn3govF2DKPdLUH
    private String accessKeyId;
    @Value("${aliyun.oss.accessKeySecret}")  //n9rABMbC8AxxXOEdKOuGDbsyoH26oo
    private String accessKeySecret;

    public String uploadFile(MultipartFile file) throws Exception {
        // 获取文件上传的输入流
        InputStream inputStream = file.getInputStream();

        //获取到文件名后缀 并重新命名
        String originalFilename = file.getOriginalFilename();
        String s = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));

        //上传到oss
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ossClient.putObject(bucketName, s, inputStream);

        //文件路径
        String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + s;

        // 关闭ossClient
        ossClient.shutdown();
        return url;
    }
}
